package com.zbkj.admin.boot.redisson.ratelimiter;

import com.zbkj.admin.boot.redisson.common.RedisNameResolver;
import net.dreamlu.mica.core.utils.ResourceUtil;
import org.redisson.api.RScript;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.LongCodec;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 基于 redis 的分布式限流自动配置
 *
 * @author L.cm
 */
@Configuration
//@ConditionalOnBean(RedissonClient.class)
//@ConditionalOnProperty(value = "redisson.rate-limiter.enable",havingValue = "true")
public class RedissonRateLimiterConfiguration {

	@Bean
	public RedisRateLimiterClient redisRateLimiter(RedissonClient client,
												   RedisNameResolver resolver) {
		RScript script = client.getScript(LongCodec.INSTANCE);
		String luaScript = ResourceUtil.getAsString("classpath:META-INF/scripts/redis_rate_limiter.lua");
		return new RedisRateLimiterClient(script, luaScript, resolver);
	}

	@Bean
	public RedisRateLimiterAspect redisRateLimiterAspect(RedisRateLimiterClient rateLimiterClient) {
		return new RedisRateLimiterAspect(rateLimiterClient);
	}
}
